<template>
  <div class="conversation-container">
    <el-card class="conversation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="card-header-title">
            聊天会话
          </div>
          <div class="card-header-option">
            <!--    新增会话按钮        -->
            <svg-icon icon-class="ai-add-conversation" size="22px" @click="newConversation"/>
          </div>
        </div>
      </template>
      <el-scrollbar height="100%">
        <div class="conversation-list">
          <template v-for="conversationsGroup in conversationGroups">
            <div class="conversation-group" style="display: flex; align-items: center; justify-content: space-between;"
                 @mouseenter="hoverGroupTitle = conversationsGroup.title"
                 @mouseleave="hoverGroupTitle = null">
              <span>{{ conversationsGroup.title }}</span>
              <svg-icon v-if="hoverGroupTitle === conversationsGroup.title" color="#f56c6c" icon-class="delete"
                        size="18px" style="cursor: pointer;" @click.stop="handleDeleteGroup(conversationsGroup.title)"/>
            </div>
            <div
                v-for="(item) in conversationsGroup.items"
                :key="item.id || ''"
                :class="{ active: (item.id || '') === (conversationId || '') }"
                class="conversation-item"
                @click="handleActive(item.id || '', conversationsGroup.title)"
                @mouseenter="onItemEnter(item.id || '')"
                @mouseleave="onItemLeave(item.id || '')"
            >
              <span v-if="(item.id || '') === (conversationId || '')" class="active-bar"></span>
              <div class="conversation-item-title">
                <svg-icon :icon-class="(item.icon || item.icon === '') ? item.icon : 'ai-default-conversation'"
                          size="22px"/>
                <span v-if="editingId !== (item.id || '')" class="conversation-name">{{ item.title }}</span>
                <input
                    v-else
                    :ref="el => setInputRef(el, item.id || '')"
                    v-model="editingName"
                    class="conversation-rename-input"
                    style="width: 100px; margin-left: 8px;"
                    @blur="handleRenameConfirm(item, conversationsGroup.title)"
                    @keyup.enter="handleRenameConfirm(item, conversationsGroup.title)"
                />
              </div>
              <div v-if="hoverIndex === (item.id || '') || dropdownVisibleIndex === (item.id || '')"
                   class="conversation-item-title">
                <el-dropdown
                    trigger="click"
                    @command="(cmd) => handleDropdownCommand(cmd, item, conversationsGroup.title)"
                    @visible-change="(visible) => onDropdownVisibleChange(visible, item.id || '')"
                >
                  <span class="el-dropdown-link" @click.stop>
                    <svg-icon icon-class="more" size="24px"/>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu @mouseenter="onDropdownEnter(item.id || '')"
                                      @mouseleave="onDropdownLeave(item.id || '')">
                      <el-dropdown-item command="rename">
                        <el-icon>
                          <Edit/>
                        </el-icon>
                        重命名
                      </el-dropdown-item>
                      <el-dropdown-item command="delete">
                        <el-icon>
                          <Delete/>
                        </el-icon>
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </template>
        </div>
      </el-scrollbar>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import type {UserChatConversationVO} from '@/api/ai/chat/user-chat/type';

defineOptions({
  name: 'ConversationContainer',
  inheritAttrs: false,
});

const props = defineProps<{
  conversationGroups: { title: string; items: UserChatConversationVO[] }[];
  conversationId: string;
  draftConversationId: string;
}>();

const emits = defineEmits<{
  (e: 'new'): void;
  (e: 'active', payload: { groupTitle: string; itemId: string }): void;
  (e: 'delete', payload: { groupTitle: string; itemId: string }): void;
  (e: 'rename', payload: { groupTitle: string; itemId: string; newTitle: string }): void;
  (e: 'delete-group', payload: { groupTitle: string }): void;
}>();

const hoverIndex = ref<string | null>(null);
const dropdownVisibleIndex = ref<string | null>(null);
const editingId = ref<string | null>(null);
const editingName = ref('');
const inputRefs = ref<Record<string, HTMLInputElement | null>>({});
const hoverGroupTitle = ref<string | null>(null);

function setInputRef(el: any, id: string) {
  if (el instanceof HTMLInputElement) {
    inputRefs.value[id] = el;
  }
}

function focusInput(id: string) {
  nextTick(() => {
    setTimeout(() => {
      inputRefs.value[id]?.focus();
    }, 0);
  });
}

function onItemEnter(idx: string) {
  hoverIndex.value = idx;
}

function onItemLeave(idx: string) {
  if (dropdownVisibleIndex.value !== idx) {
    hoverIndex.value = null;
  }
}

function onDropdownVisibleChange(visible: boolean, idx: string) {
  dropdownVisibleIndex.value = visible ? idx : null;
  if (!visible) hoverIndex.value = null;
}

function onDropdownEnter(idx: string) {
  dropdownVisibleIndex.value = idx;
}

function onDropdownLeave(idx: string) {
  dropdownVisibleIndex.value = null;
  hoverIndex.value = null;
}

function handleDropdownCommand(command: string, item: UserChatConversationVO, groupTitle: string) {
  if (command === 'rename') {
    editingId.value = item.id || '';
    editingName.value = item.title || '';
    focusInput(item.id || '');
  } else if (command === 'delete') {
    ElMessageBox.confirm(`确认删除会话【${item.title}】吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true,
    }).then(() => {
      emits('delete', {groupTitle, itemId: item.id!});
    });
  }
}

function handleRenameConfirm(item: UserChatConversationVO, groupTitle: string) {
  if (editingName.value.trim()) {
    emits('rename', {groupTitle, itemId: item.id!, newTitle: editingName.value.trim()});
  }
  editingId.value = null;
}

function handleDeleteGroup(groupTitle: string) {
  ElMessageBox.confirm(`确认删除分组【${groupTitle}】的所有会话吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    dangerouslyUseHTMLString: true,
  }).then(() => {
    emits('delete-group', {groupTitle});
  });
}

function handleActive(itemId: string, groupTitle: string) {
  emits('active', {groupTitle, itemId});
}

function newConversation() {
  emits('new');
}
</script>

<style lang="scss" scoped>
.conversation-container {
  height: 100%;
  width: 260px;

  .conversation-card {
    height: 100%;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.card-header-title {
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-header-option {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  transition: color 0.2s;

  &:hover {
    color: var(--el-color-primary);
  }
}

.conversation-card {
  box-shadow: 0 4px 24px 0 rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.conversation-group {
  padding: 6px 12px;
  font-size: 14px;
  font-weight: 600;
  line-height: 26px;
}

:deep(.el-card__header) {
  height: 10%;
}

:deep(.el-card__body) {
  padding: 0 0 0;
  height: 90%;
}

.conversation-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.conversation-item {
  position: relative;
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: background 0.2s;
  padding: 0 12px;

  &:hover {
    background-color: var(--el-color-primary-light-9);
  }
}

.active-bar {
  position: absolute;
  left: 0;
  top: 0;
  width: 4px;
  height: 100%;
  background: var(--el-color-primary-light-3);
  display: block;
  z-index: 1;
}

.conversation-item-title {
  display: flex;
  align-items: center;
  gap: 12px;
  position: relative;
  overflow: hidden;
  white-space: nowrap;
}

.conversation-name {
  min-width: 0;
  flex: 1;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  display: block;
}

.conversation-item.active {
  display: flex;
  background-color: var(--el-color-primary-light-9);
}

.conversation-rename-input {
  border: 1px solid var(--el-color-primary-light-7);
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s;

  &:focus {
    border-color: var(--el-color-primary);
  }
}

</style>